package com.yzl.meeting.business.service.Impl;

import com.yzl.meeting.business.dao.UserDao;
import com.yzl.meeting.business.dao.impl.UserDaoImpl;
import com.yzl.meeting.business.entity.User;
import com.yzl.meeting.business.exception.BusinessException;
import com.yzl.meeting.business.rule.ResponseCode;
import com.yzl.meeting.business.service.UserService;
import com.yzl.meeting.business.utils.CommonsUtils;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Title: UserServiceImpl
 * @Author: 姚志立
 * @Description:
 * @Date: 2020/10/9 15:13
 * @Version: 1.0
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    /**
     * 先查找用户名是否存在
     * 再比较密码是否相等
     *
     * 登录成功后，为用户添加一个token
     * @return
     */
    public User login(User loginUser) throws Exception {
        User user = userDao.findUserByUserName(loginUser.getUserName());
        if(user == null){
            throw new BusinessException(ResponseCode.USERNAMEERROR);
        }
        if(!loginUser.getPassword().equals(user.getPassword())){
            throw new BusinessException(ResponseCode.PASSWORDERROR);
        }

        /*
        给用户一个令牌
        使用uuid作为令牌
         */
        String token = CommonsUtils.getUUID();
        user.setToken(token);
//        user.setLastLoginTime(new DateTime());
        userDao.update(user);

        return user;
    }

    @Override
    public void logout(User loginUser) throws Exception {
        loginUser.setToken("");
        userDao.update(loginUser);
    }

    @Override
    public User findUserByUserName(String userName) throws Exception {
        User userByUserName = userDao.findUserByUserName(userName);
        return userByUserName;
    }

    @Override
    public void update(User user) throws Exception {
        userDao.update(user);
    }

    @Override
    public void verifyPassword(User user) throws Exception {
        User u = userDao.findUserByUserName(user.getUserName());
        if(!u.getPassword().equals(user.getPassword())){
            throw new BusinessException(ResponseCode.PASSWORDERROR);
        }
    }
}